package com.xcx.baseManger.service.impl;


import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.xcx.baseManger.helper.Message;
import com.xcx.baseManger.helper.User;
import com.xcx.baseManger.service.MessageService;
import com.xcx.commoncore.request.messagerequest.QueryMessageListRequest;
import com.xcx.commonuntils.returnuntls.ReturnMessage;
import com.xcx.commonuntils.returnuntls.ReturnMessageUtils;
import lombok.RequiredArgsConstructor;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Primary
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MessageServiceImpl implements MessageService {


    final private MongoTemplate mongoTemplate;


    /**
     * 查询消息历史记录
     * 用户a-b
     *
     * @param fromId
     * @param toId
     * @param page
     * @param rows
     * @return
     */
    @Override
    public List<Message> findListFromAndTo(Integer fromId, Integer toId, Integer page, Integer rows) {


        //用户A发送用户B条件
        Criteria criteriaFrom = new Criteria().andOperator(
                Criteria.where("from.user_id").is(fromId),
                Criteria.where("to.user_id").is(toId)
        );

        //用户B发送用户A条件
        Criteria criteriaTo = new Criteria().andOperator(
                Criteria.where("from.user_id").is(toId),
                Criteria.where("to.user_id").is(fromId)
        );

        //设置分页
        Criteria criteria = new Criteria().orOperator(criteriaFrom, criteriaTo);
        PageRequest pageRequest = PageRequest.of(page - 1, rows, Sort.by(Sort.Direction.ASC, "send_date"));

        //设置分页条件
        Query query = Query.query(criteria).with(pageRequest);

        return mongoTemplate.find(query, Message.class);
    }


    /**
     * 根据组件id查询
     *
     * @param id
     * @return
     */
    @Override
    public Message findMessageById(String id) {

        return mongoTemplate.findById(new ObjectId(id), Message.class);
    }


    /**
     * 通过opid查询用户信息
     *
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {

        Query query = new Query(Criteria.where("username").is(username));
        User user = mongoTemplate.findOne(query, User.class);
        return user;
    }


    /**
     * 保存消息信息
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public UpdateResult updateMessageState(Object id, Integer status) {
        Query query = Query.query(Criteria.where("id").is(id));
        Update update = Update.update("status", status);
        if (status.intValue() == 1) {
            update.set("send_date", new Date());
        } else if (status.intValue() == 2) {
            update.set("read_date", new Date());
        }
        return mongoTemplate.updateFirst(query, update, Message.class);
    }

    /**
     * 更新用户角色
     *
     * @param user
     */
    @Override
    public void updateUser(User user) {
        Query query = new Query(Criteria.where("id").is(user.getId()));
        Update update = new Update().set("role_id", user.getRoleId());
        mongoTemplate.updateFirst(query, update, User.class);


    }


    @Override
    public Message saveMessage(Message message) {
        message.setSendDate(new Date());
        message.setStatus(1);
        message.setId(ObjectId.get());
        return mongoTemplate.save(message);
    }

    @Override
    public void saveUser(User user) {
        mongoTemplate.save(user);
    }


    @Override
    public DeleteResult deleteMessage(String id) {
        Query query = new Query(Criteria.where("id").is(id));


        return null;
    }


    @Override
    public void deleteById(String username) {
        Query query = new Query(Criteria.where("username").is(username));
        mongoTemplate.remove(query, User.class);
    }


    /**
     * 获取聊天消息记录
     *
     * @param registerVo
     * @return
     */
    @Override
    public ReturnMessage<Object> queryMessageList(QueryMessageListRequest registerVo) {
        User toUsername = findByUsername(registerVo.getUsernameTo());

        User fromUsername = findByUsername(registerVo.getUsernameFrom());

        List<Message> listFromAndTo = findListFromAndTo(fromUsername.getUserId(), toUsername.getUserId(), registerVo.getPage(), registerVo.getRows());
        listFromAndTo.stream().forEach(message -> {
            if (message.getStatus().intValue() == 1) {
                updateMessageState(message.getId(), 2);
            }
        });
        return ReturnMessageUtils.success(listFromAndTo);
    }





}
